package exam.security;


import cn.hutool.core.util.StrUtil;
import exam.bean.UserInfo;
import exam.service.impl.UserInfoServiceImpl;
import exam.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserDetailServiceImpl userDetailService;

    @Autowired
    UserInfoServiceImpl userInfoService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwt = request.getHeader(jwtUtils.getHeader());
        //当请求头中不存在token时，从请求体中获取token数据
        if(jwt == null){
            jwt = request.getParameter("parameter");
        }

        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request, response);
            return;
        }

        Claims claim = jwtUtils.getClaimByToken(jwt);
        if (claim == null) {
            throw new JwtException("token 异常");
        }
        if (jwtUtils.isTokenExpired(claim)) {
            throw new JwtException("token已过期");
        }

        //获取用户信息
        String username = claim.getSubject();

        //获取用户权限等信息

        Map<String,Object> queryMap =  new HashMap<>();
        queryMap.put("name",username);
        UserInfo userInfo = userInfoService.selectInfoSingle(queryMap);


        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,null,userDetailService.getUserAuthority(userInfo));
        SecurityContextHolder.getContext().setAuthentication(token);

//        System.out.println("token获取且自动登录");
        chain.doFilter(request, response);

    }
}
